import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    debugShowCheckedModeBanner: false,
    home: AnimatedListPage(),
  ));
}

class AnimatedListPage extends StatefulWidget {
  const AnimatedListPage({super.key});

  @override
  State<AnimatedListPage> createState() => _AnimatedListPageState();
}

class _AnimatedListPageState extends State<AnimatedListPage> {
  final globalKey = GlobalKey<AnimatedListState>();
  List<String> list = ["第一条数据", "第二条数据"];
  bool flag = true;
  Widget _buildItem(context, index) {
    return ListTile(
      key: ValueKey(index),
      title: Text(list[index]),
      trailing: IconButton(
        onPressed: () {
          _deleteItem(index);
        },
        icon: const Icon(Icons.delete),
      ),
    );
  }

  _deleteItem(index) {
    if (flag == true) {
      flag = false;
      print('index: $index');
      globalKey.currentState!.removeItem(index, (context, animation) {
        list.removeAt(index);
        var item = _buildItem(context, index);
        return FadeTransition(
          opacity: animation,
          child: item,
        );
      }, duration: const Duration(milliseconds: 500));
      Timer.periodic(const Duration(milliseconds: 600), (timer) {
        flag = true;
        timer.cancel();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("AppBar组件"),
      ),
      body: AnimatedList(
        key: globalKey,
        itemBuilder: (context, index, animation) {
          return FadeTransition(
            opacity: animation,
            child: _buildItem(context, index),
          );
        },
        initialItemCount: list.length,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            list.add("这是一条数据");
            globalKey.currentState!.insertItem(list.length - 1);
          });
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
